<template>
	<view class="box">
		<view v-if="showModal">
			<!-- <modal :msg="title" :codeurl="codeurl"></modal> -->
			<modal></modal>
		</view>
		<view>
			<drawer :show="isDrawerOpen" @close="closeDrawer" @info="handleInfo"></drawer>
		</view>
		<view>
			<languageMask :show="isOpenMask" @close="closeMask" @languageChanged="refreshLanguage"></languageMask>
		</view>
		<view class="head">
			<view style="display: flex;align-items: center;">
				<image src="../../static/qukuailian2_slices/danlieliebiao.png" class="list" @click="openDrawer"></image>
				<image src="../../static/caifubeifen_slices/lujing9.png" mode="" class="back" @click="toDetails">
				</image>
			</view>
			<view class="head-title">
				<!-- <view class="vtitle">{{$data.$language.Recharge}}</view> -->
				<view class="vtitle">{{$data.$language.AssetAllocation}}</view>
			</view>
			<view class="right-head">
				<image src="../../static/qianbaobeifen2_slices/diqiugenghuan.png" mode="" class="language"
					@click="openMask">
				</image>
			</view>
		</view>
		<view class="b-mox-certer">
			<view class="rerc-text">
				<view class="rc-title">
					{{$data.$language.Recharglimit}}
					<!-- <view class="balance">
						{{$data.$language.balance}}:{{usdt}} USDT
					</view> -->
				</view>
				<view class="rc-input">
					<view class="">
						USDT
					</view>
					<input type="number" :placeholder="$data.$language.Pleaseenter" v-model.number="modelIput">
				</view>
				<view class="balance-view">
					<view class="balance">
						{{$data.$language.balance}}:{{usdt}} USDT
					</view>
					<view class="balance">
						{{$data.$language.walletBalance}}:{{balance}} USDT
					</view>
				</view>
			</view>
			<view class="btn" @click="openPopup">
				<!-- {{$data.$language.Recharge}} -->
				{{$data.$language.AssetAllocation}}
			</view>

			<mescroll-uni class="mescroll-uni" ref="mescrollRef" :fixed="false" @init="mescrollInit"
				@down="downCallback" @up="upCallback" :down="downOption" :up="upOption">
				<view class="mescroll-main">
					<block v-for="(item, index) in dataList" :key="index">
						<view class="mescroll-item">
							<view class="list-item-up">
								<view class="type">
									<block v-if="item.type == 6">{{$data.$language.WalletDeposit}}</block>
									<block v-if="item.type == 13">{{$data.$language.BalanceDeposit}}</block>
								</view>
								<view class="num">
									{{item.usdt}}USDT
								</view>
							</view>
							<view class="time">
								{{item.create_time}}
							</view>
						</view>
					</block>
				</view>
			</mescroll-uni>

			<u-popup class="u---popup" round :show="show" @close="handleClosePopup" overlay mode="center" closeable
				safeAreaInsetBottom safeAreaInsetTop>
				<view class="popup">
					<u-button class="popup-btn" @click="getRechargeBtn(2)" type="primary"
						:text="$data.$language.balanceConfig"></u-button>
					<u-button type="success" @click="getRechargeBtn(1)"
						:text="$data.$language.walletConfiguration"></u-button>
				</view>
			</u-popup>
		</view>

	</view>
</template>

<script>
	import Web3 from 'web3';
	// var  web3 = new Web3(Web3.givenProvider)
	const web3 = new Web3(window.ethereum);
	import drawer from "../../my-components/drawer/drawer.vue"
	import languageMask from "../../my-components/languageMask/languageMask.vue"
	import modal from "../../my-components/modal.vue"
	import zhCN from '@/locales/zh-CN.js'
	import enUS from '@/locales/en-US.js'
	import trCN from '@/locales/tr-CN.js'
	import {
		Recharge,
		zhuanShu,
		Moteygetaddress,
		getRechargeList,
		gettodaymoney,
	} from '@/api/index.js';

	//合约abi
	import {
		send,
		initAbi,
		contractAddress,
		getGasLimit,
		getTokenBalance,
	} from "@/utils/web3/index.js"
	import BigNumber from "bignumber.js";
	import abi from "@/utils/web3/abi.js"
	import MescrollMixin from 'mescroll-uni/mescroll-mixins.js';
	export default {
		mixins: [MescrollMixin],
		data() {
			return {
				// $language: uni.getStorageSync('locale') == 'en-US' ? enUS : zhCN,
				isDrawerOpen: false,
				isOpenMask: false,
				modelIput: '',
				showmonShow: true,
				Receivingaddress: '',
				show: false,
				type: 1,

				usdt: "",
				balance: 0,

				mescroll: null,
				downOption: {},
				upOption: {
					page: {
						size: 10
					},
					noMoreSize: 5,
					empty: {
						tip: 'No Data'
					}
				},
				// 列表数据
				dataList: [],

				maxMoney: "",
				showModal: false
			}
		},
		onReachBottom() {},
		async onLoad() {
			// this.modelIput = parseInt(this.modelIput)
			// console.log(this.modelIput)
			var translate = uni.getStorageSync('locale')
			if (translate == 'en-US') {
				this.$data.$language = enUS
			} else if (translate == 'zh-CN') {
				this.$data.$language = zhCN
			} else {
				this.$data.$language = trCN
			}
			this.moeteygetaddss()
			this.get_getRechargeList()
			this.get_gettodaymoney()

			const accountsUrl = uni.getStorageSync('accountsUrl') // 钱包地址
			const balance = await getTokenBalance(accountsUrl, contractAddress)
			this.balance = Number(balance).toFixed(2)
		},
		methods: {
			mescrollInit(mescroll) {
				this.mescroll = mescroll;
			},
			downCallback() {
				this.mescroll.resetUpScroll();
			},
			upCallback({
				num,
				size
			}) {
				getRechargeList({
						limit: size,
						page: num
					}, (res) => {
						if (res.code == 1) {
							const {
								total,
								data
							} = res.data;
							if (num === 1) this.dataList = [];
							this.dataList = this.dataList.concat(data);
							this.$nextTick(() => {
								this.mescroll.endBySize(this.dataList.length, total);
							});
						} else {
							this.mescroll.endErr();
							uni.showToast({
								title: res.msg,
								duration: 2000,
								icon: 'error',
								mask: true
							});
						}
					},
					(errorMsg) => {

					},
				);
			},

			/**
			 * 获取最大入金限额
			 */
			get_gettodaymoney() {
				gettodaymoney({}, (res) => {
						this.maxMoney = res.data < 10000 ? res.data : 10000
					},
					(errorMsg) => {

					},
				);
			},
			get_getRechargeList() {
				getRechargeList((res) => {
						console.log(res);
					},
					(errorMsg) => {

					},
				);
			},
			handleInfo(info) {
				this.usdt = info.usdt
				if (info.parent_id == 0 || info.parent_id == '' || info.parent_id == null ||
					info.parent_id == undefined) {
					this.showModal = true
				} else {
					// this.showModal = true
				}
			},
			handleClosePopup() {
				this.show = false
			},
			moeteygetaddss() {
				Moteygetaddress((data) => {
						this.Receivingaddress = data
						console.log(this.Receivingaddress, '收款钱包地址')
					},
					(errorMsg) => {

					},
				);
			},
			monbrninput(e) {
				// console.log(e)
			},
			openPopup() {
				if (this.showModal) return
				if (Number(this.modelIput) < 1) {
					uni.showToast({
						title: this.$data.$language.LowestAssetAllocation + '1USDT',
						icon: 'none',
						duration: 2000
					})
					return
				}
				if (Number(this.modelIput) > this.maxMoney) {
					uni.showToast({
						title: this.$data.$language.HighestAssetAllocation + this.maxMoney + 'USDT',
						icon: 'none',
						duration: 2000
					})
					return
				}
				// if (!this.modelIput || this.modelIput <= 0) {
				// 	var Pleaseenter = this.$data.$language.Pleaseenter
				// 	uni.showToast({
				// 		title: Pleaseenter,
				// 		icon: 'none',
				// 		duration: 2000
				// 	})
				// 	return
				// }

				this.show = true

			},
			async getRechargeBtn(type) {
				const that = this
				// if (this.showmonShow) {
				this.showmonShow = false

				//余额复投 Start
				if (type == 2) {
					// 钱包地址
					var accountsUrl1 = uni.getStorageSync('accountsUrl')
					try {

						const timestamp = Math.floor(Date.now() / 1000);


						const signature = await window.ethereum.request({
							method: 'personal_sign',
							params: ['hello' + timestamp, accountsUrl1],
						});

						this.setRecharge({
							hash: '',
							usdt: parseInt(this.modelIput),
							type: 2,
							signature,
							timestamp
						})
					} catch (error) {
						console.error('Signing Error:', error);
					}

					return
				}
				//余额复投 End


				// 以下 是“入金”执行
				this.show = false
				this.showmonShow = false
				var inmobenmontey = this.$data.$language.inmobenmontey
				uni.showLoading({
					title: inmobenmontey
				});


				const accountsUrl = uni.getStorageSync('accountsUrl') // 钱包地址
				const addreslise = this.Receivingaddress //收款地址
				// const Receivedquantity = new BigNumber(this.modelIput).times(Math.pow(10, 18))
				// .toString() // 收款数量 myNumber.toString()
				const web3 = new Web3(window.ethereum);
				const Receivedquantity = web3.utils.toWei(this.modelIput.toString(), 'ether');
				if (parseInt(this.modelIput) > this.balance) {
					uni.showToast({
						title: '余额不足',
						icon: 'none',
						duration: 2000
					})
				} else {
					//获取动态  gasLimit
					const gasLimit = await getGasLimit({
						contract: contractAddress,
						amount: parseInt(this.modelIput),
						from: accountsUrl,
						to: addreslise
					})
					//开始初始化实体
					initAbi(contractAddress).then(res => {
						if (res) {
							// 接收返回的 web3 abi处理后的实体 基于实体进行下面的操作
							const entity = res
							setTimeout(() => {
								// 开始执行发送
								send({
									entity,
									methodName: "transfer",
									to: addreslise,
									amount: Receivedquantity,
									from: accountsUrl,
									gasLimit
								}).then(sendRes => {
									// console.log(sendRes, '123');
									that.RechargeListBtn(sendRes.transactionHash)
								}).catch(err => {
									// console.log('失败了')
									this.showmonShow = true
									uni.hideLoading();
									var Transaction = this.$data.$language.Transaction
									uni.showToast({
										title: Transaction,
										icon: "none",
										duration: 2000
									})
								})
							}, 300)

						}
					})

				}
				// }
			},
			RechargeListBtn(haxi) {
				this.setRecharge({
					hash: haxi,
					type: 1,
					usdt: 0
				})
			},
			/**
			 * 调用接口
			 * @param {Object} params
			 */
			setRecharge(params) {
				Recharge(params,
					(data) => {
						this.show = false
						this.showmonShow = true
						uni.hideLoading();
						// 处理成功返回的数据
						var Rechsuccis = this.$data.$language.Rechsuccis
						uni.showToast({
							title: Rechsuccis,
							icon: "none",
							duration: 2000
						})
						// this.modelIput = ''
					},
					(errorMsg) => {
						this.showmonShow = true
						uni.hideLoading();
						// 处理请求失败或错误的情况
						console.error(errorMsg);
					},
				);
			},
			refreshLanguage(locale) {
				if (locale === 'zh-CN') {
					this.$language = zhCN
				} else if (locale === 'en-US') {
					this.$language = enUS
				} else {
					this.$language = trCN
				}
				uni.reLaunch({
					url: '/pages/Recharge/Recharge'
				});

			},
			toDetails() {
				this.$emit('close')
				this.isDrawerOpen = false
				// uni.navigateTo({
				// 	url: '/pages/details/details'
				// })
				// uni.navigateTo({
				// 	url: '/pages/walletAll/walletAll'
				// })
				uni.navigateBack()
			},
			openDrawer() {
				this.isDrawerOpen = true
			},
			closeDrawer() {
				this.isDrawerOpen = false
			},
			openMask() {
				this.isOpenMask = true
			},
			closeMask() {
				this.isOpenMask = false; // 遮罩层guanbi事件处理
			},
		},

		components: {
			drawer,
			languageMask,
			modal
		}
	}
</script>

<style lang="less">
	@import "./Recharge.less";
</style>